<template>
	<!-- 商品调换货选择调换为-->
	<div class="vmall-cart">
		<div class="page-content">
			<div v-if="cartList.length > 0">
				<Cart ref="cartRef" :cartList="cartList" @delete="onDelete" @select="onSelect" @minus="onMinus"
					@add="onAdd" @select1="onSelect1" />
			</div>
		</div>
		<view class="bottom-button">
            <button class="scan-btn" @click="submitOk">确认</button>
        </view>
	</div>
</template>
<script setup>
import { IMG_URL2 } from "@/config";
import { shopApi } from "@/api";
import Cart from "@/components/cart.vue";
import Empty from "@/components/empty.vue";
import { useExchangeStore } from "@/store/modules/exchange";

// Add store reference
const exchangeStore = useExchangeStore();
let loadStatus = ref('正在加载中')
const cartList = ref([]);
const totalPrice = ref(0);
const CheckAll = ref(false);
const goodsCount = ref(0);
const deleteCount = ref(0);
const showBottom = ref(false);
let orderNo = ref('')
let createTime = ref('')
let productId =ref('')
let orderid =ref('')

let code =ref('')


const EmptyImage = ref(IMG_URL2 + "empty/cart.png");
const emptyInfo = ref({
	image: EmptyImage,
	width: 300,
	height: 300,
	tip: "暂无数据"
});
// 返回顶部
const backTop = ref(0);
const cartRef = ref();

onLoad((options) => {
	productId.value = options.id;
    orderid.value = options.orderid;
	getDataDetail();
});

const submitOk=()=>{
    const selectedWithParents = cartList.value.reduce((acc, parent) => {
        // Only keep selected items from skuList with quantity > 0
        const selectedSkus = parent.skuList.filter(sku => 
            sku.selected && sku.quantity > 0
        );
        
        if (selectedSkus.length > 0) {
            acc.push({
                ...parent,
				productId: productId.value,
				productCode:code.value,
                skuList: selectedSkus,
                children: selectedSkus // Keep children in sync with skuList
            });
        }
        return acc;
    }, []);
    
    if (selectedWithParents.length === 0) {
        uni.showToast({
            title: "请选择商品并设置数量",
            icon: "none"
        });
        return;
    }
	exchangeStore.setAddedItems(selectedWithParents)

    console.log(selectedWithParents, '1111');

    uni.navigateTo({
        url: `/pages/order/goodsexchangedetails?id=${orderid.value}`
    });
}
// 全选
const onSelectAll = (e) => {
	for (let i = 0; i < cartList.value.length; i++) {
		cartList.value[i].selected = !CheckAll.value;
		for (let n = 0; n < cartList.value[i].children.length; n++) {
			cartList.value[i].children[n].selected = !CheckAll.value;
		}
	}
	CheckAll.value = !CheckAll.value;
	getSumTotal();
	getGoodsCount();
	deleteGoodsCount();
};
// 反选
const onSelect = (index) => {
	// cartList.value[index].selected = !cartList.value[index].selected;
	// for (let n = 0; n < cartList.value[index].children.length; n++) {
	// 	cartList.value[index].children[n].selected = !cartList.value[index].children[n].selected
	// }
	// CheckAll.value = !cartList.value.some((item) => item.selected == false);

	const item = cartList.value[index];
    item.selected = !item.selected;
    
    item.children.forEach(sku => {
        sku.selected = item.selected;
    });

    CheckAll.value = cartList.value.every(item => 
        item.selected && item.children.every(sku => sku.selected)
    );
	getSumTotal();
	getGoodsCount();
	deleteGoodsCount();
};

// 单个反选
const onSelect1 = (index,nindex) => {
	cartList.value[index].children[nindex].selected = !cartList.value[index].children[nindex].selected;
	CheckAll.value = !cartList.value.some((item) => item.selected == false);
	getSumTotal();
	getGoodsCount();
	deleteGoodsCount();
};
// 加
const onAdd = (index,nindex) => {
	cartList.value[index].children[nindex].quantity++;
	getSumTotal();
};
// 减
const onMinus = (index,nindex) => {
	if (cartList.value[index].children[nindex].quantity == 1) {
		return;
	}
	cartList.value[index].children[nindex].quantity--;
	getSumTotal();
};
// 单个删除选中的商品
const onDelete = (index) => {
	// 处理u-swipe-action-item不复位的问题(要放在删除操作的上方)
	cartRef.value.resetSwipeAction();
	cartList.value.splice(index, 1);
	getSumTotal();
	getGoodsCount();
	deleteGoodsCount();
};
// 批量删除选中的商品
const onDeleteAll = (e) => {
	for (let i = 0; i < cartList.value.length; i++) {
		for (let n = 0; n < cartList.value[i].children.length; n++) {
			if (cartList.value[i].children[n].selected==true) {
				cartList.value[i].children.splice(n, 1);
				deleteCount.value = n;
				if(n!=0){
					n = n - 1;
				}
			}
		}
		if(cartList.value[i].children.length==0){
			cartList.value.splice(i, 1);
			if(i!=0){
				i = i - 1;
			}
		}
		if (cartList.value[i].selected == true) {
			cartList.value.splice(i, 1);
			if(i!=0){
				i = i - 1;
			}
		}

	}
	totalPrice.value = 0;
	goodsCount.value = 0;
	deleteCount.value = 0;
	CheckAll.value = false;
};
// 删除数量方法
const deleteGoodsCount = () => {
	let count = 0;
	for (let i = 0; i < cartList.value.length; i++) {
		// if (cartList.value[i].selected) {
		// 	count = count + 1;
		// }
		for (let n = 0; n < cartList.value[i].children.length; n++) {
			if (cartList.value[i].children[n].selected) {
				// sum += cartList.value[i].children[n].quantity * cartList.value[i].children[n].price;
				count = count + 1;
			}
		}
	}
	deleteCount.value = count;
};
// 合计
const getSumTotal = () => {
	let sum = 0;
	for (let i = 0; i < cartList.value.length; i++) {
		for (let n = 0; n < cartList.value[i].children.length; n++) {
			if (cartList.value[i].children[n].selected) {
				sum += cartList.value[i].children[n].quantity * cartList.value[i].children[n].price;
			}
		}
		// if (cartList.value[i].selected) {
		// 	sum += cartList.value[i].quantity * cartList.value[i].price;
		// }
	}
	totalPrice.value = sum;
};
// 商品总数量
const getGoodsCount = () => {
	let count = 0;
	for (let i = 0; i < cartList.value.length; i++) {
		for (let n = 0; n < cartList.value[i].children.length; n++) {
			if (cartList.value[i].children[n].selected) {
				// sum += cartList.value[i].children[n].quantity * cartList.value[i].children[n].price;
				count = count + 1;
			}
		}
		// if (cartList.value[i].selected) {
		// 	count = count + 1;
		// }
	}
	goodsCount.value = count;
};
// 编辑
const onRightEdit = () => {
	showBottom.value = !showBottom.value;
};
// 取消删除功能
const onCancel = () => {
	showBottom.value = false;
};
// 结算
const onPayOrder = () => {
	if (goodsCount.value > 0) {
		uni.navigateTo({ url: "/pages/order/confirm" });
	} else {
		uni.showToast({
			title: "您还没有选择商品哦",
			icon: "none",
			mask: true
		});
	}
};

const applyAdjust = () => {
	uni.navigateTo({
        url: `/pagesshop/sales/details?id=${goodsexchangeId.value}`
    });
}
const getData = () => {
	let params = {
		id: productId.value,
	}
	shopApi.ORDERAPPLYADJUST(params).then((res) => {
		if (res.code == 200) {
			createTime.value = res.result.createTime
			orderNo.value = res.result.orderNo
			res.result.productList.forEach(item => {
				item.unitPrice = item.price
				item.productImg = item.image
				if(item.skuList&&item.skuList.length>0){
				    item.skuList.forEach(ele=>{
				        ele.skuImg = ele.image
						ele.skuSpec	= ele.spec
						ele.quantity = ele.availableQuantity
				    })
				}
				item.children= item.skuList
			});

			cartList.value =res.result.productList
		}else{
            uni.showToast({
                title: res.errMsg,
                icon: "success",
            });
        }

	})

};
const resetArray = (inputArray,item)=>{
    inputArray.forEach(element => {
        element.num=1
        element.quantity = 0
        element.PDproductSkuId= item.productSkuId
        element.PDskuCode= item.skuCode
        element.PDskuPic= item.skuPic
        element.PDinventory= item.inventory
        element.PDname= item.name
        element.skuImg= item.skuPic
        
    });
    return Object.values(inputArray.reduce((acc, current) => {
            const key = `${current.name}-${current.sort}`;
            acc[key] = current;
            return acc;
        }, {}));
    
}
const getSkuItem= (inputArray)=>{
    const result = [];

    let colorValue = '';
    let sizeValues = [];

    inputArray.forEach(item => {
        if (item.name === '颜色') {
            colorValue = item.value;
        }
        if (item.name === '尺寸') {
			console.log(item,'item')
            sizeValues.push({sizeValue:item.value,productSkuId:item.PDproductSkuId,skuCode:item.PDskuCode,skuImg:item.PDskuPic});
        }
    });

    const outputArray = sizeValues.map(items =>{
        return {
        color: colorValue,
        size: items.sizeValue,
        skuSpec:colorValue+';'+items.sizeValue,
        productSkuId: items.productSkuId,
        skuCode: items.skuCode,
        skuImg: items.skuImg,
        quantity:0
    }});
    return outputArray;
}
const getDataDetail = (Id) => {
    shopApi.CATEGORYGETFRONTPRODUCTDETAILBYID({ id: productId.value  }).then((res) => {
        if (res.code == 200) {
            console.log(res,'res')
			code.value = res.result.code
            let bannerList = res.result.images?res.result.images.split(','):''

            let newdata =res.result.skuList

            for (let i = 0; i < newdata.length; i++) {
                newdata[i].newattributeList=resetArray(newdata[i].attributeList,newdata[i])
            }
            
          
            let newSkuList = []
            newdata.forEach((sku) => {
                newSkuList.push(getSkuItem(sku.newattributeList))
            })

            console.log(newSkuList,'newSkuList')

            // const groupedMap = new Map();
            // newdata.forEach((sku) => {
            //     // 提取颜色、尺寸和库存
            //     const color = sku.newattributeList.find((attr) => attr.name === "颜色").value;
            //     const colorvalue=sku.newattributeList.find((attr) => attr.name === "颜色")
            //     console.log(sku.newattributeList.find((attr) => attr.name === "尺寸"),'1111')
            //     const sizeValue = sku.newattributeList.find((attr) => attr.name === "尺寸")
            //     const size = sku.newattributeList.find((attr) => attr.name === "尺寸").value;
            //     const inventory = sku.inventory;

            //     // 判断库存状态
            //     let status = "无货";
            //     if (inventory > 3) status = "库存充足";
            //     else if (inventory > 0) status = "库存紧张";

            //     let num = 0

            //     // 构建当前 SKU 数据
            //     const sizeData = { size,sizevalue:sizeValue,colorvalue:colorvalue, inventory, status,num,originalSku: sku };

            //     // 将数据按颜色分组
            //     if (!groupedMap.has(color)) {
            //     groupedMap.set(color, []); // 初始化分组
            //     }
            //     groupedMap.get(color).push(sizeData);
            // });

            // // 2. 转换为目标数组格式
            // const newresult = [];
            // let price = res.result.price
            // groupedMap.forEach((sizelist, name) => {
            //     newresult.push({ name,price, sizelist,checked:false });
            // });


            cartList.value[0]={
                productImg:bannerList[0],
                name:res.result.name,
                unitPrice:res.result.price,
                skuList:newSkuList.reduce((acc, cur) => acc.concat(cur), []),
                children:newSkuList.reduce((acc, cur) => acc.concat(cur), []),
            }


        } else{
            uni.showToast({
                title: res.errMsg,
                icon: "success",
            });
        }

    })
}
</script>

<style>
page {
	background-color: #ededed;
}
</style>
<style lang="scss" scoped>
.shopcartheader{
	width: 100%;
	box-sizing: border-box;
	display: flex;
	align-items: center;
	justify-content: space-between;
}
.vmall-cart {
	.header-content{
		background: #fff;
		font-family: PingFang SC;
		font-size: 12px;
		font-weight: 400;
		line-height: 20px;
		text-align: left;
		text-underline-position: from-font;
		text-decoration-skip-ink: none;
		color: rgba(0, 0, 0, 0.6);
		padding: 24rpx;
		box-sizing: border-box;
		margin-bottom: 24rpx;
	}
	.chevronright-container{
		display: flex;
		align-items: center;
		justify-content: space-between;
		background-color: #fff;
		margin-bottom: 24rpx;
		padding: 24rpx;
		box-sizing: border-box;
		.tit{
			font-family: PingFang SC;
			font-size: 12px;
			font-weight: 400;
			line-height: 20px;
			text-align: left;
			text-underline-position: from-font;
			text-decoration-skip-ink: none;
			color: rgba(0, 0, 0, 0.9);
		}
	}
	.chevronright-content {
        width: 32rpx;
        height: 32rpx;

        .chevronright {
            width: 100%;
            height: 100%;
        }
    }

	.page-content {
		.page-content-head{
			display: flex;
			align-items: center;
			justify-content: space-between;
			background-color: #fff;
			padding: 24rpx;
			box-sizing: border-box;
			.tit{
				font-family: PingFang SC;
				font-size: 12px;
				font-weight: 400;
				line-height: 20px;
				text-align: left;
				text-underline-position: from-font;
				text-decoration-skip-ink: none;
				color: rgba(0, 0, 0, 0.9);
			}
			.add-goods{
				width: 100px;
				height: 28px;
				padding: 3px 12px 3px 12px;
				box-sizing: border-box;
				gap: 4px;
				border-radius: 20px;
				opacity: 0px;
				color:#fff;
				background:rgba(214, 142, 68, 1);
				text-align: center;
			}
		}
		.cart-main {
			display: flex;
			margin-right: 20rpx;
		}

		.cart-active {
			float: left;
			width: 100%;
			background: #ffffff;
			border-bottom: 2rpx solid #f2f2f2;
		}

		.cart-image {
			width: 200rpx;
			height: 200rpx;
			float: left;
			margin: 20rpx 10rpx;
		}

		.cart-box {
			display: flex;
			background: white;
			border-radius: 8rpx;
		}

		.cart-boxtwo {
			display: flex;
			flex-direction: column;
		}

		.left_box {
			margin-left: 8rpx;
			margin-top: 20rpx;
			line-height: 60rpx;
		}

		.cart-title {
			font-size: 28rpx;
			line-height: 34rpx;
			display: -webkit-box;
			-webkit-box-orient: vertical;
			overflow: hidden;
			-webkit-line-clamp: 2;
		}

		.cart-count {
			display: flex;
			justify-content: space-between;
			align-items: center;
		}

		.cart-unit {
			font-size: 24rpx;
			color: rgba(214, 142, 68, 1);
		}

		.cart-money {
			display: flex;
			align-items: center;
		}

		.cart-price {
			display: flex;
			color: rgba(214, 142, 68, 1);
			font-size: 30rpx;
			height: 36rpx;
			line-height: 36rpx;
		}

		.cart-specif {
			padding: 4rpx 12rpx;
			box-sizing: border-box;
			background: rgba(214, 142, 68, 1);
			color: #ffffff;
			font-size: 24rpx;
			height: 36rpx;
			line-height: 36rpx;
			margin-bottom: 10rpx;
			border-radius: 50rpx;
		}

		.right {
			float: right;
			width: 5%;
		}

		.right image {
			width: 50rpx;
			height: 50rpx;
			float: right;
			margin-right: 30rpx;
		}

		.input {
			display: block;
			width: 65rpx;
			height: 65rpx;
			line-height: 65rpx;
			text-align: center;
			float: left;
		}

		.cart-add {
			border-left: none;
			border: 2rpx solid #ededed;
			border-radius: 0rpx 40rpx 40rpx 0rpx;
			font-size: 36rpx;
		}

		.cart-reduce {
			border-right: none;
			border: 2rpx solid #ededed;
			border-radius: 40rpx 0rpx 0rpx 40rpx;
			font-size: 36rpx;
		}

		.cart-text {
			width: 90rpx;
			border-top: 2rpx solid #ededed;
			border-bottom: 2rpx solid #ededed;
			font-size: 30rpx;
		}

		.cart-bottom {
			display: flex;
			position: fixed;
			width: 100%;
			height: 88rpx;
			bottom: var(--window-bottom);
			background: #ffffff;
			padding: 0rpx 20rpx;
			box-sizing: border-box;
			border-top: 2rpx solid #f2f2f2;
			z-index: 999;
		}

		.cart-bottom-icon {
			margin-top: 22rpx;

			image {
				width: 40rpx !important;
				height: 40rpx !important;
			}
		}

		.yuan {
			display: block;
			width: 50rpx;
			height: 50rpx;
			border-radius: 50%;
			border: 2rpx solid red;
		}

		.SpCart {
			display: block;
			width: 300rpx;
			height: 300rpx;
		}

		.Sptext {
			font-size: 30rpx;
		}

		.cart-icon {
			margin: 26rpx 20rpx;
			float: left;
		}

		.cart-sum {
			width: 300rpx;
			height: 100%;
			line-height: 87rpx;
			float: left;
			text-align: center;
			margin-left: 20rpx;
			font-size: 28rpx;
		}

		.cart-pay {
			position: absolute;
			width: 230rpx;
			height: 100%;
			background: rgba(214, 142, 68, 1);
			right: 0;
		}

		.cart_pay {
			display: block;
			line-height: 87rpx;
			text-align: center;
			font-size: 30rpx;
			color: white;
		}

		.sum_color {
			color: rgba(214, 142, 68, 1);
			font-size: 25rpx;
		}

		.sum_text {
			font-size: 30rpx;
		}

		.checkAll {
			margin-left: 20rpx;
			line-height: 87rpx;
			font-size: 28rpx;
		}

		.cart-cell {
			display: flex;
			padding: 20rpx 20rpx 0rpx 20rpx;
			box-sizing: border-box;
		}

		.nodata_text {
			background: #ffffff;
			color: black;
			font-size: 28rpx;
			text-align: center;
		}

		.nodata_text {
			image {
				margin-top: 100rpx;
				width: 44%;
				height: 300rpx;
			}
		}

		.icon-main {
			margin: 94rpx 20rpx;
			background: #ffffff;

			image {
				width: 40rpx !important;
				height: 40rpx !important;
			}
		}

		.empty-container {
			background: #ffffff;
		}

		/* 底部 */
		.del-bottom {
			position: fixed;
			width: 100%;
			height: 88rpx;
			bottom: var(--window-bottom);
			background: #ffffff;
			border-top: 2rpx solid #f2f2f2;
			z-index: 999;
		}

		.cart-bottom-edit {
			float: left;
			width: 100%;
			height: 88rpx;
			line-height: 88rpx;
			text-align: center;
			font-size: 28rpx;
			color: rgba(214, 142, 68, 1);
		}

		.cart-bottom-cell {
			float: left;
			width: 49.725%;
			height: 88rpx;
			line-height: 88rpx;
			text-align: center;
			font-size: 28rpx;
			color: #999999;
			border-right: 2rpx solid #f2f2f2;
		}

		.cart-bottom-cell:last-child {
			border-right: 0rpx;
		}

		.del-color {
			color: rgba(214, 142, 68, 1);
		}
	}

	.wrap {
		padding: 0rpx 10rpx 100rpx 10rpx;
		box-sizing: border-box;
	}

	:deep .u-empty {
		background: #ffffff;
		margin-bottom: 40rpx;
		padding-bottom: 40rpx;
	}
}
.bottom-button {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 20rpx;
    box-sizing: border-box;
    background-color: #fff;
    box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.scan-btn {
    background-color: rgba(214, 142, 68, 1);
    color: #fff;
    border: none;
    width: 100%;
    height: 80rpx;
    line-height: 80rpx;
    border-radius: 40rpx;
    font-size: 32rpx;
}

.cart-right {
	font-size: 26rpx;
}

:deep .u-status-bar {
	display: none !important;
}
</style>